package AwsSES;

import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.ec2.model.Address;
import com.amazonaws.services.simpleemail.AmazonSimpleEmailService;
import com.amazonaws.services.simpleemail.AmazonSimpleEmailServiceClient;
import com.amazonaws.services.simpleemail.model.*;
import com.amazonaws.services.simpleworkflow.flow.TimerException;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.mail.BodyPart;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.util.ByteArrayDataSource;

public class SenderEmail {

    public static final String ACCESS_KEY = "AKIAJICRH6ZVS7ENHQMA";
    public static final String SECRET_KEY = "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";
    public static final String SENDER = "bsm@brunomaria.com.br";

    public void emailSimples(String body, String assunto, List<String> destinatarios) {

        AWSCredentials credentials = new BasicAWSCredentials(ACCESS_KEY, SECRET_KEY);
        AmazonSimpleEmailServiceClient sesClient = new AmazonSimpleEmailServiceClient(credentials);

        try {

            Content assuntoContent = new Content(assunto);
            Content bodyContent = new Content(body);
            Body msgBody = new Body(bodyContent);

            Message mensagem = new Message(assuntoContent, msgBody);

            Destination destination = new Destination(destinatarios);

            SendEmailResult resultado;
            SendEmailRequest request = new SendEmailRequest(SENDER, destination, mensagem);

            resultado = sesClient.sendEmail(request);
            System.out.println("MENSAGEM ENVIADA: Nº - " + resultado.getMessageId());

        } catch (MessageRejectedException mr) {
            System.out.println("EXCEPTION: " + mr.getMessage());

        } catch (Exception e) {
            System.out.println("EXCEPTION: " + e.getMessage());
        }
    }

    public void emailAnexo(MimeMessage mensagem, List<String> anexos) {

        AWSCredentials credentials = new BasicAWSCredentials(ACCESS_KEY, SECRET_KEY);
        AmazonSimpleEmailServiceClient sesClient = new AmazonSimpleEmailServiceClient(credentials);
        
        try {
            
            if (anexos != null) {

                Multipart multipart = new MimeMultipart();
                multipart = anexarArquivosPorNome(multipart, anexos);
                mensagem.setContent(multipart);
                mensagem.saveChanges();

            }

            //TRANSFORMA A MENSAGEM DE BYTES
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            mensagem.writeTo(outputStream);

            RawMessage rawMessage = new RawMessage(ByteBuffer.wrap(outputStream.toByteArray()));
            SendRawEmailRequest request = new SendRawEmailRequest(rawMessage);

            SendRawEmailResult retorno = sesClient.sendRawEmail(request);

            System.out.println("MENSAGEM ENVIADA: Nº - " + retorno.getMessageId());


        } catch (MessageRejectedException mr) {
            mr.printStackTrace();
        } catch (TimerException t) {
            t.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void verifyEmailAddress(AmazonSimpleEmailService ses, String address) {

        ListVerifiedEmailAddressesResult verifiedEmails = ses.listVerifiedEmailAddresses();

        if (verifiedEmails.getVerifiedEmailAddresses().contains(address)) {
            return;
        }

        ses.verifyEmailAddress(new VerifyEmailAddressRequest().withEmailAddress(address));
        System.out.println("Please check the email address " + address + " to verify it");
        System.exit(0);

    }

    private static Multipart anexarArquivosPorNome(Multipart multipart, List<String> listaAnexos) throws Exception {
        if (listaAnexos != null && listaAnexos.size() > 0) {

            FileInputStream fis = null;

            for (String anexo : listaAnexos) {

                try {

                    BodyPart fileBodyPart = new MimeBodyPart();

                    String caminhoArquivo = anexo;
                    File arquivo = new File(caminhoArquivo);
                    fis = new FileInputStream(arquivo);

                    //ESSE TIPO DE CODIFICACAO ABRANGE UMA GAMA MAIOR DE ARQUIVOS
                    DataSource source = new ByteArrayDataSource(fis, "application/octet-stream");
                    fileBodyPart.setDataHandler(new DataHandler(source));

                    //NOME DO ARQUIVO NO EMAIL
                    String filename = arquivo.getName();
                    fileBodyPart.setFileName(filename);
                    multipart.addBodyPart(fileBodyPart);

                } catch (Exception e) {
                    e.printStackTrace();

                } finally {

                    try {
                        if (fis != null) {
                            fis.close();
                        }
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
                }

            }

        }
        return multipart;
    }
}
